package edu.buu.refectory.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class EncryptUtil {

	/**
	 * des密钥
	 */
	private static final String DESKEY = "12345678";
	
	/**
	 * des向量
	 */
	private static final String DESIV = "12345678";
	
	/**
	 * 加密 des&base64
	 * @param data
	 * @return
	 * @throws Exception
	 */
	private static String encrypt(String data){
		String str = "";
		try {
			Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			 DESKeySpec desKeySpec = new DESKeySpec(DESKEY.getBytes("UTF-8"));
			 SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
			 SecretKey secretKey = factory.generateSecret(desKeySpec);
			 IvParameterSpec iv = new IvParameterSpec(DESIV.getBytes("UTF-8"));
			 cipher.init(Cipher.ENCRYPT_MODE, secretKey,iv);
			 byte[] source = cipher.doFinal(data.getBytes());
			 BASE64Encoder encoder = new BASE64Encoder();
			 str = encoder.encodeBuffer(source);
		} catch (Exception e) {
			e.printStackTrace();
		}	 
		 return str;
	}
	
	/**
	 * 解密
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(String data) throws Exception{
		BASE64Decoder decoder = new BASE64Decoder();
		byte[] bytedata = decoder.decodeBuffer(data);
		Cipher cipher =Cipher.getInstance("DES/CBC/PKCS5Padding");
		DESKeySpec desKeySpec = new DESKeySpec(DESKEY.getBytes("UTF-8"));
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
		IvParameterSpec iv = new IvParameterSpec(DESIV.getBytes("UTF-8"));
		cipher.init(Cipher.DECRYPT_MODE, secretKey,iv);
		byte[] retByte = cipher.doFinal(bytedata);
		return new String(retByte,"gb2312");
	}
	
	/**
	 * base64加密
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public static String base64_encrypt(String data) throws Exception{		
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(encrypt(data).getBytes());
	}
}
